/**
 * 
 */
package com.yunyike.controller.merchandise;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yunyike.constants.CommonConstant;
import com.yunyike.constants.ExcelConstants;
import com.yunyike.constants.RequestConstant;
import com.yunyike.constants.ResponseConstant;
import com.yunyike.controller.BaseController;
import com.yunyike.dto.MerchandiseDTO;
import com.yunyike.dto.QuotationMerchandiseDTO;
import com.yunyike.model.Brand;
import com.yunyike.model.Merchandise;
import com.yunyike.model.Price;
import com.yunyike.model.Quotation;
import com.yunyike.model.Sku;
import com.yunyike.model.SkuSummary;
import com.yunyike.service.BrandService;
import com.yunyike.service.MerchandiseService;
import com.yunyike.service.PriceService;
import com.yunyike.service.QuotationService;
import com.yunyike.service.SkuService;
import com.yunyike.service.SkuSummaryService;
import com.yunyike.utils.QuotationMerchandiseExcelUtil;

@Controller
@RequestMapping(value=RequestConstant.MERCHANDISE)
public class MerchandiseController extends BaseController{

	private Logger log = LoggerFactory.getLogger(MerchandiseController.class);
	
	@Autowired
	private QuotationService quotationService;
	
	@Autowired
	private MerchandiseService merchandiseService;
	@Autowired
	private SkuService skuService;
	@Autowired
	private PriceService priceService;
	@Autowired
	private BrandService brandService;
	@Autowired
	private SkuSummaryService skuSummaryService;
	
	
	@RequestMapping(value=RequestConstant.MERCHANDISELIST+"/{quotationId}/{skuStatu}")
	public String toReviewList(HttpServletRequest request, HttpServletResponse response,
			@PathVariable(value="quotationId") String quotationId,
			@PathVariable(value="skuStatu") String skuStatu) {
		log.info("MERCHANDISELIST getList --进入excel商品列表页--quotationId="+quotationId+",skuStatu="+skuStatu);
		if(StringUtils.isBlank(quotationId)){
			request.setAttribute("message", "请求参数有误，稍后重试");
			return ResponseConstant.REDIRECT+RequestConstant.QUOTATION+RequestConstant.QUOTATION_LIST+"/0/1";
		}
		request.setAttribute("quotationId", quotationId);
		request.setAttribute("skuStatu", skuStatu);
		request.setAttribute("skuStatusMap", CommonConstant.getSkuStatusMap());
		request.setAttribute("statusMap", CommonConstant.getStatusMap());
		if(!"1".equals(skuStatu)&&!"3".equals(skuStatu))skuStatu="3";
		List<QuotationMerchandiseDTO> list = new ArrayList<QuotationMerchandiseDTO>();
		try {
			Quotation quotation = quotationService.selectByPrimaryKey(quotationId);
			if (quotation != null) {
				request.setAttribute("quotationName", quotation.getQuotationName());
				String excelName = quotation.getQuotationLink().replace(ExcelConstants.EXCEL_SAVEPATH, "");
				if (!"".equals(quotation.getQuotationLink())) {
					String middleexcel = ExcelConstants.EXCEL_MIDDLEPATH+ excelName;
					File file = new File(middleexcel);
					if(file.exists()){
						log.info("中间excel表已存在，获取excel数据---");
						if("3".equals(skuStatu))
							QuotationMerchandiseExcelUtil
								.readMiddleExcel(middleexcel, list,"",CommonConstant.MERCHANDISE_REVIEW+"");
						if("1".equals(skuStatu))
							QuotationMerchandiseExcelUtil
								.readMiddleExcel(middleexcel, list,CommonConstant.SKU_STOCKPILING_REVIEW+"","");
					
						request.setAttribute("quotMerchlist", list);
						return ResponseConstant.MERCHANDISELIST;
					}else{
						log.info("中间excel表不存在--");
						request.setAttribute("message", "表格还未提交审核");
					}
				}
			} else {
				request.setAttribute("message", "请求参数有误，稍后重试");
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("message", "发生异常");
		}
		return ResponseConstant.MERCHANDISELIST;
	}
	
//	statu :4==发布批准；2==囤货批准
	@ResponseBody
	@RequestMapping(value = RequestConstant.MERCHANDISEPUSH + "/{quotationId}/{statu}")
	public String saveMerchandise(String ids, HttpServletRequest request, HttpServletResponse response,
			@PathVariable(value = "quotationId") String quotationId,
			@PathVariable(value="statu") String statu) {
		log.info("MERCHANDISE push---ids="+ids+",statu="+statu);
		if(StringUtils.isBlank(ids)){
			return "未获取到发布或囤货信息";
		}
		if("-1".equals(statu))statu = CommonConstant.MERCHANDISE_ONSALE+"";
		try{
			String[] idsArr = ids.split("_");
			Map<String,Integer> stockQtyMap = new HashMap<String,Integer>();
			if("2".equals(statu)){
				String stockQtys = request.getParameter("stockQtys");
				String[] rowAndQty = stockQtys.split("_");
				for(int i =0;i<rowAndQty.length;i++){
					String[] tempArr = rowAndQty[i].split(":");
					if(tempArr.length==2)
						stockQtyMap.put(tempArr[0], Integer.parseInt(tempArr[1]));
				}
			}
			Quotation quotation = quotationService.selectByPrimaryKey(quotationId);
			List<MerchandiseDTO> merchDtoList  = QuotationMerchandiseExcelUtil
					.readMerchandise(quotation, idsArr,statu,stockQtyMap);
			log.info("MERCHANDISE 从excel中获取需要处理的数据--条数："+merchDtoList.size());
			int savedNum = saveMerchandiseDTO(merchDtoList,quotationId,stockQtyMap);
			log.info("MERCHANDISE 保存商品等相关信息入库：成功商品条数："+savedNum);
			if(savedNum>0){
				QuotationMerchandiseExcelUtil.modifyPush(quotation,statu,merchDtoList);
				if(CommonConstant.NUMBER_4>quotation.getQuotationStatus()&&"4".equals(statu)){
					quotation.setQuotationStatus(CommonConstant.NUMBER_4);
					quotationService.updateByPrimaryKeySelective(quotation);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			return "发生异常";
		}
		
		return "success";
	}

	private int saveMerchandiseDTO(List<MerchandiseDTO> merchDtoList,
			String quotationId,Map<String,Integer> stockQtyMap){
		int num = 0;
		if(merchDtoList!=null&&merchDtoList.size()>0){
			for(MerchandiseDTO dto:merchDtoList){
				Merchandise merch = dto.getMerch();
				Sku merchSku = dto.getMerchSku();
				Price merchPrice = dto.getMerchPrice();
				boolean newMerch = dto.isNewMerch();
				if(newMerch){
					Brand brand = brandService.selectBrandByQuotationId(quotationId);
					if(brand!=null)merch.setMerchandiseBrand(brand.getBrandId());
					int merchnum = merchandiseService.insert(merch);
					if(merchnum>0){
						int skunum = skuService.insert(merchSku);
						if(skunum>0){
							int pricenum = priceService.insert(merchPrice);
							if(pricenum>0) num++;
							saveStockQty(stockQtyMap, merchSku.getSkuId());
						}
					}
				}else{
					int merchnum = merchandiseService.updateByPrimaryKeySelective(merch);
					if(merchnum>0){
						int skunum = skuService.updateByPrimaryKeySelective(merchSku);
						if(skunum>0){
							int pricenum = priceService.updateByPrimaryKeySelective(merchPrice);
							if(pricenum>0) num++;
							saveStockQty(stockQtyMap, merchSku.getSkuId());
						}
					}
				}
				
			}
		}
		return num;
	}
	
	private Integer saveStockQty(Map<String,Integer> stockQtyMap,String skuId){
		int num = 0;
		if(null !=stockQtyMap &&stockQtyMap.size()>0){
			SkuSummary summary = skuSummaryService.selectBySkuId(skuId);
			if(summary==null){
				summary = new SkuSummary();
				summary.setSkuSummaryId(UUID.randomUUID().toString());
				summary.setSkuId(skuId);
				summary.setSkuSummaryQty(stockQtyMap.get(skuId));
				if(null!=stockQtyMap.get(skuId))
					num = skuSummaryService.insert(summary);
			}else{
				summary.setSkuSummaryQty(stockQtyMap.get(skuId));
				if(null!=stockQtyMap.get(skuId))
					num = skuSummaryService.updateByPrimaryKeySelective(summary);
			}
		}
		return num;
	}
	
	@ResponseBody
	@RequestMapping(value = RequestConstant.MERCHANDISEBACK + "/{quotationId}/{skuSatu}")
	public String backMerchandise(String ids, HttpServletRequest request, HttpServletResponse response,
			@PathVariable(value = "quotationId") String quotationId,
			@PathVariable(value = "skuSatu") String skuSatu) {
		log.info("MERCHANDISE backMerchandise---ids="+ids+",skuSatu="+skuSatu+",quotationId="+quotationId);
		if(StringUtils.isBlank(ids)){
			return "未获取到信息";
		}
		if("-1".equals(skuSatu))skuSatu = CommonConstant.MERCHANDISE_REVIEW+"";
		try{
			String[] idsArr = ids.split("_");
			Quotation quotation = quotationService.selectByPrimaryKey(quotationId);
			String excelName = quotation.getQuotationLink().replace(ExcelConstants.EXCEL_SAVEPATH, "");
			log.info("更新[ "+excelName+" ]表格的部分商品信息的状态，"+idsArr.length+"行商品信息");
			int num = 0;
			for(int i =0;i<idsArr.length;i++){
				if("".equals(idsArr[i]))continue;
				int rowNum = Integer.parseInt(idsArr[i]);
				QuotationMerchandiseDTO exportDTO = new QuotationMerchandiseDTO();
				exportDTO.setRowIndex(rowNum);
				if("3".equals(skuSatu)){
					exportDTO.setStatus(CommonConstant.MERCHANDISE_BACK);
				}else{
					exportDTO.setSkuStatus(CommonConstant.SKU_STOCKPILING_BACK);
				}
				String message = QuotationMerchandiseExcelUtil.modifyMerchandiseStatu(exportDTO, excelName, ExcelConstants.EXCEL_MIDDLEPATH);
				if("".equals(message)){
					num++;
				}
			}
			log.info("退回"+num+"商品数据");
			if(idsArr.length!=num){
				return "部分退回操作失败";
			}
		}catch(Exception e){
			e.printStackTrace();
			return "发生异常";
		}
		log.info("MERCHANDISE backMerchandise--END-");
		return "success";
	}
}
